import hashlib
from io import BytesIO

from django.core.validators import RegexValidator
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django import forms
from web import models
from web.models import User, Scenic, Message, Bookinfo, ImageList
from web.utils.code import check_code
from web.utils.pagination import Pagination


def mainindex(request):
    return render(request, 'mainindex.html')

def main(request):
    usercount = User.objects.filter().count()
    sceniccount = Scenic.objects.filter().count()
    bookinfocount = Bookinfo.objects.filter().count()
    messagecount = Message.objects.filter().count()
    image_list = ImageList.objects.filter(level=2).all()
    context = {
        "usercount":usercount,
        "sceniccount": sceniccount,
        "bookinfocount": bookinfocount,
        "messagecount": messagecount,
        "image_list":image_list,
    }
    return render(request, 'index_v1.html',context)

# 用户模块方法
class UserModelForm(forms.ModelForm):
    username = forms.CharField(min_length=3, label="用户名")
    phone = forms.CharField(
        label="手机号",
        
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误'), ],
    )
    email = forms.CharField(
        label="邮箱",
        validators=[RegexValidator(r'^[0-9a-za-z_]{0,19}@[0-9a-za-z]{1,13}\.[com,cn,net]{1,3}$', '邮箱格式错误'), ],
    )
    class Meta:
        model = models.User
        fields = ["username", "password", "email", 'phone', "gender"]
        # widgets = {
        #     "email": forms.EmailInput(attrs={"class": "form-control", "placeholder": "邮箱"}),
        #
        # }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加了class="form-control"
        for name, field in self.fields.items():
            # if name == "email":
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label, "required":""}


def mainuser_list(request):
    """用户列表"""
    queryset = models.User.objects.filter().all()

    page_object = Pagination(request, queryset)

    context = {
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html()  # 页码
    }
    return render(request, "mainuser_list.html", context)

def mainuser_listadd(request):
    """ 添加用户（ModelForm版本）"""
    if request.method == "GET":
        form = UserModelForm()
        return render(request, 'mainuser_listadd.html', {"form": form})

    # 用户POST提交数据，数据校验。
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        salt = "xueguanchao"
        Encry = hashlib.md5(salt.encode("utf-8"))
        password = form.cleaned_data["password"]
        Encry.update(password.encode())
        md5_pwd = Encry.hexdigest()
        models.User.objects.create(username=form.cleaned_data["username"], password=md5_pwd,
                                   email=form.cleaned_data["email"], phone=form.cleaned_data["phone"],
                                   gender=form.cleaned_data["gender"])
        return redirect('/mainuser/list/')

    # 校验失败（在页面上显示错误信息）
    return render(request, 'mainuser_listadd.html', {"form": form})

def mainuser_listedit(request, nid):
    """ 编辑用户（ModelForm版本）"""
    row_object = models.User.objects.filter(id=nid).first()
    if request.method == "GET":
        # 根据id获取数据，使用form提交数据
        form = UserModelForm(instance=row_object)
        return render(request, 'mainuser_listedit.html', {"form": form})
    # 用户POST提交数据，数据校验。
    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        # {'name': '123', 'password': '123', 'age': 11, 'account': Decimal('0'), 'create_time': datetime.datetime(2011, 11, 11, 0, 0, tzinfo=<UTC>), 'gender': 1, 'depart': <Department: IT运维部门>}
        # print(form.cleaned_data)
        # models.UserInfo.objects.create(..)
        salt = "xueguanchao"
        Encry = hashlib.md5(salt.encode("utf-8"))
        password = form.cleaned_data["password"]
        Encry.update(password.encode())
        md5_pwd = Encry.hexdigest()
        models.User.objects.filter(id=nid).update(username=form.cleaned_data["username"], password=md5_pwd,
                                   email=form.cleaned_data["email"], phone=form.cleaned_data["phone"],
                                   gender=form.cleaned_data["gender"])
        # form.save()
        return redirect('/mainuser/list/')

    # 校验失败（在页面上显示错误信息）
    return render(request, 'mainuser_listedit.html', {"form": form})

def mainuser_listdelete(request, nid):
    """ 删除用户（ModelForm版本）"""
    models.User.objects.filter(id=nid).delete()
    return redirect('/mainuser/list/')


# 管理员模块方法
class AdminModelForm(forms.ModelForm):
    adminname = forms.CharField(min_length=3, label="管理员名")
    class Meta:
        model = models.Admin
        fields = ["adminname", "password"]
        # widgets = {
        #     "email": forms.EmailInput(attrs={"class": "form-control", "placeholder": "邮箱"}),
        #
        # }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加了class="form-control"
        for name, field in self.fields.items():
            # if name == "email":
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

def mainadmin_list(request):
    """管理员列表"""
    queryset = models.Admin.objects.filter().all()

    page_object = Pagination(request, queryset)

    context = {
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html()  # 页码
    }
    return render(request, "mainadmin_list.html", context)

def mainadmin_listadd(request):
    """ 添加管理员（ModelForm版本）"""
    if request.method == "GET":
        form = AdminModelForm()
        return render(request, 'mainadmin_listadd.html', {"form": form})

    # 用户POST提交数据，数据校验。
    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/mainadmin/list/')

    # 校验失败（在页面上显示错误信息）
    return render(request, 'mainadmin_listadd.html', {"form": form})


def mainadmin_listedit(request, nid):
    """ 编辑用户（ModelForm版本）"""
    row_object = models.Admin.objects.filter(id=nid).first()
    if request.method == "GET":
        # 根据id获取数据，使用form提交数据
        form = AdminModelForm(instance=row_object)
        return render(request, 'mainadmin_listedit.html', {"form": form})
    # 用户POST提交数据，数据校验。
    form = AdminModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/mainadmin/list/')

    # 校验失败（在页面上显示错误信息）
    return render(request, 'mainadmin_listedit.html', {"form": form})


def mainadmin_listdelete(request, nid):
    """ 删除管理员（ModelForm版本）"""
    models.Admin.objects.filter(id=nid).delete()
    return redirect('/mainadmin/list/')

class LoginForm(forms.Form):
    '''登录'''
    adminname = forms.CharField(
        label="用户名",
        widget=forms.TextInput
    )
    password = forms.CharField(
        label="密码",
        widget=forms.PasswordInput
    )
    code = forms.CharField(
        label="验证码",
        widget=forms.TextInput,
        required=True
    )
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加了class="form-control"
        for name, field in self.fields.items():
            # if name == "password":
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label, "required":""}


def admin_login(request):
    """ 登录 """
    if request.method == "GET":
        form = LoginForm()
        return render(request, 'adminlogin.html', {'form': form})

    form = LoginForm(data=request.POST)
    if form.is_valid():
        # 验证成功，获取到的用户名和密码
        # 验证码的校验
        user_input_code = form.cleaned_data.pop('code')
        code = request.session.get('image_code', "")
        if code.upper() != user_input_code.upper():
            form.add_error("code", "验证码错误")
            return render(request, 'adminlogin.html', {'form': form})

        # 去数据库校验用户名和密码是否正确，获取用户对象、None
        admin_object = models.Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            form.add_error("password", "用户名或密码错误")
            # form.add_error("username", "用户名或密码错误")
            return render(request, 'adminlogin.html', {'form': form})

        # 用户名和密码正确
        # 网站生成随机字符串; 写到用户浏览器的cookie中；在写入到session中；
        request.session["info"] = {'id': admin_object.id, 'adminname': admin_object.adminname}
        # session可以保存7天
        request.session.set_expiry(60 * 60 * 24 * 7)

        return redirect("/mainindex/main/")

    return render(request, 'login.html', {'form': form})

def admin_logout(request):
    request.session.clear()
    return redirect("/admin/login/")

def image_code(request):
    """ 生成图片验证码 """

    # 调用pillow函数，生成图片
    img, code_string = check_code()

    # 写入到自己的session中（以便于后续获取验证码再进行校验）
    request.session['image_code'] = code_string
    # 给Session设置60s超时
    request.session.set_expiry(60)

    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())
